package org.apache.seatunnel.connectors.seatunnel.gaussdbredis.sink;

import org.apache.seatunnel.api.serialization.SerializationSchema;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
import org.apache.seatunnel.connectors.seatunnel.common.sink.AbstractSinkWriter;
import org.apache.seatunnel.connectors.seatunnel.gaussdbredis.config.GaussDBRedisDataType;
import org.apache.seatunnel.connectors.seatunnel.gaussdbredis.config.GaussDBRedisParameters;
import org.apache.seatunnel.format.json.JsonSerializationSchema;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class GaussDBRedisSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void> {
    private final SeaTunnelRowType seaTunnelRowType;
    private final GaussDBRedisParameters redisParameters;
    private final SerializationSchema serializationSchema;
    private final Jedis jedis;

    public GaussDBRedisSinkWriter(SeaTunnelRowType seaTunnelRowType, GaussDBRedisParameters redisParameters) {
        this.seaTunnelRowType = seaTunnelRowType;
        this.redisParameters = redisParameters;
        this.serializationSchema = new JsonSerializationSchema(seaTunnelRowType);
        this.jedis = redisParameters.buildJedis();
    }

    @Override
    public void write(SeaTunnelRow element) throws IOException {
        String data = new String(serializationSchema.serialize(element));
        GaussDBRedisDataType redisDataType = redisParameters.getGaussDBRedisDataType();
        String keyField = redisParameters.getKeyField();
        List<String> fields = Arrays.asList(seaTunnelRowType.getFieldNames());
        String key;
        if (fields.contains(keyField)) {
            key = element.getField(fields.indexOf(keyField)).toString();
        } else {
            key = keyField;
        }
        redisDataType.set(jedis, key, data);
    }

    @Override
    public void close() throws IOException {
        if (Objects.nonNull(jedis)) {
            jedis.close();
        }
    }
}
